package com.molichuxing.gateway.bff.order.services.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.molichuxing.gateway.bff.order.convertor.Convert;
import com.molichuxing.gateway.bff.order.entity.response.CarOrderVo;
import com.molichuxing.gateway.bff.order.entity.response.OrderAuditVo;
import com.molichuxing.gateway.bff.order.entity.response.OrderContractVo;
import com.molichuxing.gateway.bff.order.entity.response.OrderTradeRefundVo;
import com.molichuxing.gateway.bff.order.entity.response.UserOrderVo;
import com.molichuxing.gateway.bff.order.services.OrderBffService;
import com.molichuxing.services.business.dto.response.CarCheckDto;
import com.molichuxing.services.business.dto.response.CarOrderBizDto;
import com.molichuxing.services.business.dto.response.OrderBizDto;
import com.molichuxing.services.business.dto.response.OrderExclusivelBizDto;
import com.molichuxing.services.business.dto.response.OrderSubscribeBizDto;
import com.molichuxing.services.business.dto.response.UserBizDto;
import com.molichuxing.services.business.dto.response.UserOrderBizDto;
import com.molichuxing.services.business.service.CarCheckBizService;
import com.molichuxing.services.business.service.OrderBizService;
import com.molichuxing.services.business.service.UserBizService;
import com.molichuxing.services.infrastructure.dto.response.ContractDto;
import com.molichuxing.services.infrastructure.dto.response.OrderDeliveryDto;
import com.molichuxing.services.infrastructure.dto.response.OrderDto;
import com.molichuxing.services.infrastructure.dto.response.OrderExclusivelStatusFlowDto;
import com.molichuxing.services.infrastructure.dto.response.OrderReturnDto;
import com.molichuxing.services.infrastructure.dto.response.OrderSubscribeStatusFlowDto;
import com.molichuxing.services.infrastructure.dto.response.StoreDto;
import com.molichuxing.services.infrastructure.service.ContractService;
import com.molichuxing.services.infrastructure.service.OrderAuditService;
import com.molichuxing.services.infrastructure.service.OrderDeliveryService;
import com.molichuxing.services.infrastructure.service.OrderReturnService;
import com.molichuxing.services.infrastructure.service.OrderService;
import com.molichuxing.services.infrastructure.service.OrderStatusFlowService;
import com.molichuxing.services.infrastructure.service.StoreService;
import com.molichuxing.services.property.ContractTypeEnum;
import com.molichuxing.services.property.DocumentTypeEnum;
import com.molichuxing.services.property.OrderExclusivelStatusEnum;
import com.molichuxing.services.property.OrderSubscribeStatusEnum;
import com.molichuxing.services.property.OrderTypeEnum;

@Service("orderBffService")
public class OrderBffServiceImpl implements OrderBffService {
	private static final Logger logger = LoggerFactory.getLogger(OrderBffServiceImpl.class);

	@Resource
	private OrderService orderService;

	@Resource
	private OrderBizService orderBizService;

	@Resource
	private StoreService storeService;

	@Resource
	private UserBizService userBizService;

	@Resource
	private ContractService contractService;

	@Resource
	private CarCheckBizService carCheckBizService;

	@Resource
	private OrderReturnService orderReturnService;

	@Resource
	private OrderDeliveryService orderDeliveryService;

	@Resource
	private OrderAuditService orderAuditService;

	@Resource
	private OrderStatusFlowService orderStatusFlowService;

	/**
	 * 根据用户id获取订单信息
	 * 
	 * @param userId
	 *            用户id
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<UserOrderVo> getOrderByUser(Integer userId) throws Exception {
		List<UserOrderVo> result = null;

		List<UserOrderBizDto> userOrderBizDtoList = orderBizService.getOrderByUser(userId);
		if (userOrderBizDtoList == null || userOrderBizDtoList.isEmpty()) {
			return result;
		}

		result = new ArrayList<>();
		// 门店id集合
		List<Integer> storeIds = new ArrayList<>();
		// 车型id集合
		List<Integer> vehicleIds = new ArrayList<>();
		for (UserOrderBizDto userOrderBizDto : userOrderBizDtoList) {
			storeIds.add(userOrderBizDto.getPlaceStoreId());
			vehicleIds.add(userOrderBizDto.getVehicleId());
			result.add(Convert.toUserOrderVo(userOrderBizDto));
		}

		// 查询门店
		Map<Integer, StoreDto> storeMap = storeService.getStoreMapByIds(storeIds);
		// 查询车型
//		Map<Integer, Object> vehicleMap = new HashMap<>();
//		if ((storeMap == null || storeMap.size() <= 0) && (vehicleMap == null || vehicleMap.size() <= 0)) {
//			return result;
//		}

		for (UserOrderVo userOrderVo : result) {
			// 门店
			StoreDto storeDto = storeMap == null ? null
					: storeMap.isEmpty() ? null : storeMap.get(userOrderVo.getPlaceStoreId());
			// 下单门店(简称)
			userOrderVo.setPlaceStoreName(storeDto == null ? null : storeDto.getShortName());
			// 车型名称
			// orderExclusivelVo.setVehicleName(vehicleName);
		}

		return result;
	}

	/**
	 * 根据车辆id获取订单信息
	 * 
	 * @param carId
	 *            车辆id
	 * @param dealerId
	 *            经销商id
	 * @return
	 */
	@Override
	public List<CarOrderVo> getOrderByCar(Integer carId, Integer dealerId) throws Exception {
		List<CarOrderVo> result = null;
		// 根据经销商id查询经销商下门店id
		List<Integer> dealerStoreIds = storeService.getAllStoreIdByDealer(dealerId);
		if (dealerStoreIds == null || dealerStoreIds.isEmpty()) {
			return result;
		}
		List<CarOrderBizDto> carOrderBizDtoList = orderBizService.getOrderByCar(carId, dealerStoreIds);
		if (carOrderBizDtoList == null || carOrderBizDtoList.isEmpty()) {
			return result;
		}

		result = new ArrayList<>();
		// 门店id集合
		List<Integer> storeIds = new ArrayList<>();
		// 用户id集合
		List<Integer> userIds = new ArrayList<>();
		for (CarOrderBizDto carOrderBizDto : carOrderBizDtoList) {
			storeIds.add(carOrderBizDto.getDeliveryStoreId());
			userIds.add(carOrderBizDto.getUserId());
			result.add(Convert.toCarOrderVo(carOrderBizDto));
		}

		// 查询门店
		Map<Integer, StoreDto> storeMap = storeService.getStoreMapByIds(storeIds);
		// 查询用户
		Map<Integer, UserBizDto> userMap = userBizService.getUsers(userIds);
		if ((storeMap == null || storeMap.size() <= 0) && (userMap == null || userMap.size() <= 0)) {
			return result;
		}

		for (CarOrderVo carOrderVo : result) {
			// 门店
			StoreDto storeDto = storeMap == null ? null
					: storeMap.isEmpty() ? null : storeMap.get(carOrderVo.getDeliveryStoreId());
			// 下单门店(简称)
			carOrderVo.setDeliveryStoreName(storeDto == null ? null : storeDto.getShortName());
			// 用户
			UserBizDto userBizDto = userMap == null ? null
					: userMap.isEmpty() ? null : userMap.get(carOrderVo.getUserId());
			// 用户名
			carOrderVo.setUserName(userBizDto == null ? null : userBizDto.getRealName());
		}

		return result;
	}

	/**
	 * 根据订单号获取订单单据或合同信息
	 * 
	 * @param orderCode
	 *            订单号
	 * @param documentType
	 *            类型 1：单据，2：合同
	 * @return
	 * @throws Exception
	 */
	@Override
	public List<OrderContractVo> getOrderContract(Long orderCode, DocumentTypeEnum documentType) throws Exception {
		List<OrderContractVo> result = null;

		List<ContractDto> contractDtos = contractService.getContractList(orderCode, documentType);
		if (contractDtos == null || contractDtos.isEmpty()) {
			return result;
		}
		// 判断类型
		if (DocumentTypeEnum.CONTRACT.equals(documentType)) {
			result = Convert.toOrderContractVo(contractDtos);
		} else if (DocumentTypeEnum.SHEET.equals(documentType)) {
			result = new ArrayList<>();
			// 查询订单信息
			OrderBizDto orderBizDto = orderBizService.getOrder(orderCode);

			// 查询门店顾问和车辆里程
			for (ContractDto contractDto : contractDtos) {
				OrderContractVo vo = Convert.toOrderContractVo(contractDto);
				if (contractDto.getContractType() == ContractTypeEnum.MILEAGE_BAG_CAR_CONTRACT.getValue()) {
					// 交车单
					OrderDeliveryDto orderDeliveryDto = orderDeliveryService.getOrderDelivery(orderCode);
					if (orderDeliveryDto != null) {
						vo.setContractTypeStr("交车单");
						vo.setContractName("订阅里程服务交车单");
						vo.setSignedTime(orderDeliveryDto.getDeliveryTime());
						vo.setSalesmanName(orderDeliveryDto.getSalesmanName());
					}
				} else if (contractDto.getContractType() == ContractTypeEnum.MILEAGE_BAG_RETURN_CAR.getValue()) {
					// 还车单
					OrderReturnDto orderReturnDto = orderReturnService.getOrderReturn(orderCode);
					if (orderReturnDto != null) {
						vo.setContractTypeStr("还车单");
						vo.setContractName("订阅里程服务还车单");
						vo.setSignedTime(orderReturnDto.getReturnTime());
						vo.setSalesmanName(orderReturnDto.getSalesmanName());
					}
				}

				result.add(setMileage(vo, orderBizDto, contractDto.getContractType()));
			}

			// 查询验车单据
			List<CarCheckDto> carCheckDtos = carCheckBizService.getCheckByOrderCode(orderCode);
			if (carCheckDtos != null && !carCheckDtos.isEmpty()) {
				for (CarCheckDto carCheckDto : carCheckDtos) {
					if (carCheckDto.getType() == 2) {
						OrderContractVo vo = new OrderContractVo();
						vo.setContractTypeStr("验车单");
						vo.setContractName("订阅里程服务验车单");
						vo.setMileage(carCheckDto.getMileage());
						vo.setSignedTime(carCheckDto.getCheckTime());
						vo.setSalesmanName(carCheckDto.getOpName());
						result.add(vo);
					}
				}
			}
		}
		return result;
	}

	private OrderContractVo setMileage(OrderContractVo vo, OrderBizDto orderBizDto, int contractType) {
		if (OrderTypeEnum.EXCLUSIVEL.equals(orderBizDto.getType())) {
			// 专属里程订单
			OrderExclusivelBizDto orderExclusivelBizDto = (OrderExclusivelBizDto) orderBizDto;
			if (contractType == ContractTypeEnum.CAR_CONTRACT.getValue()) {
				// 交车单
				vo.setMileage(orderExclusivelBizDto.getStartMileage() == null ? null
						: new BigDecimal(orderExclusivelBizDto.getStartMileage()));
			}
		} else if (OrderTypeEnum.SUBSCRIBE.equals(orderBizDto.getType())) {
			// 订阅里程订单
			OrderSubscribeBizDto orderSubscribeBizDto = (OrderSubscribeBizDto) orderBizDto;
			if (contractType == ContractTypeEnum.MILEAGE_BAG_CAR_CONTRACT.getValue()) {
				// 交车单
				vo.setMileage(orderSubscribeBizDto.getStartMileage() == null ? null
						: new BigDecimal(orderSubscribeBizDto.getStartMileage()));
			} else if (contractType == ContractTypeEnum.MILEAGE_BAG_RETURN_CAR.getValue()) {
				// 还车单
				vo.setMileage(orderSubscribeBizDto.getSettleMileage() == null ? null
						: new BigDecimal(orderSubscribeBizDto.getSettleMileage()));
			}
		}
		return vo;
	}

	/**
	 * 获取订单审核信息
	 * 
	 * @param orderCode
	 *            订单号
	 * @return
	 */
	@Override
	public OrderAuditVo getOrderAudit(Long orderCode) {
		return Convert.toOrderAuditVo(orderAuditService.getOrderAudit(orderCode));
	}

	/**
	 * 获取订单交易退款信息
	 * 
	 * @param orderCode
	 *            订单号
	 * @return
	 * @throws Exception
	 */
	@Override
	public OrderTradeRefundVo getOrderTradeRefund(Long orderCode) throws Exception {
		OrderTradeRefundVo result = null;
		OrderDto orderDto = orderService.getOrder(orderCode);
		if (orderDto == null) {
			return result;
		}
		if (OrderTypeEnum.EXCLUSIVEL.equals(orderDto.getType())) {
			// 专属订单
			List<OrderExclusivelStatusFlowDto> statusFlows = orderStatusFlowService
					.getExclusivelOrderStatusFlow(orderCode);
			if (statusFlows == null || statusFlows.isEmpty()) {
				return result;
			}
			result = new OrderTradeRefundVo();
			for (OrderExclusivelStatusFlowDto statusFlowDto : statusFlows) {
				if (OrderExclusivelStatusEnum.TRADE_REFUND.equals(statusFlowDto.getOrderStatus())) {
					// 退款中
					result.setIssueId(statusFlowDto.getOrderUserId());
					result.setIssueName(statusFlowDto.getOrderUserName());
					result.setIssueTime(statusFlowDto.getOrderModifiedTime());
				} else if (OrderExclusivelStatusEnum.TRADE_FINISH.equals(statusFlowDto.getOrderStatus())) {
					// 已完成
					result.setFinishId(statusFlowDto.getOrderUserId());
					result.setFinishName(statusFlowDto.getOrderUserName());
					result.setFinishTime(statusFlowDto.getOrderModifiedTime());
				}
			}
		} else if (OrderTypeEnum.SUBSCRIBE.equals(orderDto.getType())) {
			// 订阅订单
			List<OrderSubscribeStatusFlowDto> statusFlows = orderStatusFlowService
					.getSubscribeOrderStatusFlow(orderCode);
			if (statusFlows == null || statusFlows.isEmpty()) {
				return result;
			}
			result = new OrderTradeRefundVo();
			for (OrderSubscribeStatusFlowDto statusFlowDto : statusFlows) {
				if (OrderSubscribeStatusEnum.TRADE_REFUND.equals(statusFlowDto.getOrderStatus())) {
					// 退款中
					result.setIssueId(statusFlowDto.getOrderUserId());
					result.setIssueName(statusFlowDto.getOrderUserName());
					result.setIssueTime(statusFlowDto.getOrderModifiedTime());
				} else if (OrderSubscribeStatusEnum.TRADE_FINISH.equals(statusFlowDto.getOrderStatus())) {
					// 已完成
					result.setFinishId(statusFlowDto.getOrderUserId());
					result.setFinishName(statusFlowDto.getOrderUserName());
					result.setFinishTime(statusFlowDto.getOrderModifiedTime());
				}
			}
		}
		return result;
	}
}
